#include "SignalHandler.h"

SignalHandler* SignalHandler::instance = NULL;
EventHandler* SignalHandler::signal_handlers[NSIG];

SignalHandler::SignalHandler() {
}

SignalHandler* SignalHandler::getInstance() {
	if (instance == NULL)
		instance = new SignalHandler();
	return instance;
}

void SignalHandler::destruir() {
	if (instance != NULL) {
		delete (instance);
		instance = NULL;
	}
}

EventHandler* SignalHandler::registrarHandler(int signum, EventHandler* eh) {
	EventHandler* old_eh = SignalHandler :: signal_handlers[signum];
	SignalHandler::signal_handlers[signum] = eh;

	struct sigaction sa;
	sa.sa_handler = SignalHandler::dispatcher;
	sa.sa_flags = 0;
	sigemptyset(&sa.sa_mask);	// Inicializa la mascara de señales a bloquear durante la ejecución del handler como vacío.
	sigaddset(&sa.sa_mask, signum);
	sigaction(signum, &sa, 0);	// Cambiar acción de la señal.

	return old_eh;
}

void SignalHandler::dispatcher (int signum) {
	if(SignalHandler::signal_handlers[signum] != 0 )
		SignalHandler::signal_handlers[signum]->handleSignal(signum);
}

int SignalHandler::removerHandler(int signum) {
	SignalHandler::signal_handlers[signum] = NULL;
	return 0;
}
